/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.app.tabs.service.impl;

import me.zhengjie.modules.app.hotel.service.dto.HotelInfoDto;
import me.zhengjie.modules.app.tabs.domain.TabsInfo;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.app.tabs.repository.TabsInfoRepository;
import me.zhengjie.modules.app.tabs.service.TabsInfoService;
import me.zhengjie.modules.app.tabs.service.dto.TabsInfoDto;
import me.zhengjie.modules.app.tabs.service.dto.TabsInfoQueryCriteria;
import me.zhengjie.modules.app.tabs.service.mapstruct.TabsInfoMapper;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.system.service.dto.UserDto;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Haojie Li
* @date 2021-03-01
**/
@Service
@RequiredArgsConstructor
public class TabsInfoServiceImpl implements TabsInfoService {

    private final TabsInfoRepository tabsInfoRepository;
    private final TabsInfoMapper tabsInfoMapper;

    @Override
    public Map<String,Object> queryAll(TabsInfoQueryCriteria criteria, Pageable pageable){
    	JwtUserDto jwtUserDto = (JwtUserDto) SecurityUtils.getCurrentUser();
		
		UserDto userDto = jwtUserDto.getUser();
		List<HotelInfoDto> hotelLists = new ArrayList<HotelInfoDto>(userDto.getHotels());
		if(hotelLists.size() == 1) {
			criteria.setHotelId(hotelLists.get(0).getId().toString());
		}
        Page<TabsInfo> page = tabsInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(tabsInfoMapper::toDto));
    }

    @Override
    public List<TabsInfoDto> queryAll(TabsInfoQueryCriteria criteria){
        return tabsInfoMapper.toDto(tabsInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public TabsInfoDto findById(String id) {
        TabsInfo tabsInfo = tabsInfoRepository.findById(id).orElseGet(TabsInfo::new);
        ValidationUtil.isNull(tabsInfo.getId(),"TabsInfo","id",id);
        return tabsInfoMapper.toDto(tabsInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TabsInfoDto create(TabsInfo resources) {
        resources.setId(IdUtil.simpleUUID()); 
        resources.setCreateBy(SecurityUtils.getCurrentUsername());
        resources.setCreateTime(LocalDateTime.now());
        resources.setIsEnable(1);
        return tabsInfoMapper.toDto(tabsInfoRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TabsInfo resources) {
    	resources.setUpdateBy(SecurityUtils.getCurrentUsername());
    	resources.setUpdateTime(LocalDateTime.now());
    	
        TabsInfo tabsInfo = tabsInfoRepository.findById(resources.getId()).orElseGet(TabsInfo::new);
        ValidationUtil.isNull( tabsInfo.getId(),"TabsInfo","id",resources.getId());
        tabsInfo.copy(resources);
        tabsInfoRepository.save(tabsInfo);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            tabsInfoRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<TabsInfoDto> all, HttpServletResponse response) throws IOException {
    	DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> list = new ArrayList<>();
        for (TabsInfoDto tabsInfo : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("所属酒店", tabsInfo.getHotelName());
            map.put("选项卡按钮名称", tabsInfo.getTabName());
            map.put("选项卡按钮图标", tabsInfo.getTabIcon());
            map.put("选项卡选中的按钮图标", tabsInfo.getTabIconSelected());
            map.put("创建者", tabsInfo.getCreateBy());
            map.put("更新者", tabsInfo.getUpdateBy());
            map.put("创建时间", tabsInfo.getCreateTime()  == null ? "" : dtf.format(tabsInfo.getCreateTime()));
            map.put("更新时间", tabsInfo.getUpdateTime() == null ? "" : dtf.format(tabsInfo.getUpdateTime()));
            map.put("数据状态", tabsInfo.getIsEnable());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}